package ihm.actions.files;

import ihm.controllers.ATKcontroller;
import ihm.views.character_creator.CharacterCreator;
import ihm.views.options.ATKjOptionPane;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

import systems.languages.MultiLanguages;

/**
 * @author Baptiste Legrand and Benjamin Orman
 * @version 1.0
 */
public class NewAction implements ActionListener {

  private ATKcontroller controller;

  public NewAction(ATKcontroller controller)
  {
    this.controller = controller;
  }

  @Override
  public void actionPerformed(ActionEvent e)
  {
    System.out.println("[NewAction] - Action perfomed Debut");
    int response;
    boolean saved = false;
    //if the model has been modified ...
    if(this.controller.getModel().isDirty()) 
    {
      //...we ask the user if he wants to continue without saving the current character
      while(!saved)
      {
        response = ATKjOptionPane.showConfirmDialog(
            null,
            MultiLanguages.getProperties("dialog.saveBeforeNew.text").replaceAll("$n", "<br/>"),
            MultiLanguages.getProperties("dialog.saveBeforeNew.title"),
            JOptionPane.YES_NO_CANCEL_OPTION, //Options : Yes No Cancel
            JOptionPane.QUESTION_MESSAGE,
            new ImageIcon(MultiLanguages.getProperties("dialog.saveBeforeNew.icon")) //icon
        );
        //"The current file is not save. Do you want to save the current character before create a new one ?"
        /*
         * Response :
         * -1 - Closed    -> Do nothing;
         * 0  - Yes / Ok  -> Save or Save as
         * 1  - No        -> Create a new Character
         * 2  - Cancel    -> Do nothing;
         */
        if(response == -1 || response == 2)
          return; //Do nothing
        else if(response == 0)
        {
          try {
            //TODO Alors la j'ai ecrit TODO mais je sais plus pourquoi donc dans le doute je le laisse
            SaveLoadAction.Save(controller);
            saved = true;
          } catch (IOException e1) {
            System.out.println("Error during Save "+e1.getMessage());
            e1.printStackTrace();
          }
        }
        else if(response == 1)
        {
          this.createNewCharacter(); //Create a new character
          break;
        }
      }
    }
    else
    {
      //... If the model is clean then we display the Character Creator Frame.
      this.createNewCharacter(); //Create a new character 
    }
    System.out.println("[NewAction] - Action perfomed Fin");
  }

  public void createNewCharacter()
  {
    new CharacterCreator(this.controller);
  }
}
